package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5Password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void add(EmployeeDTO employeeDTO) {
        checkParams(employeeDTO);
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
//        添加员工 默认密码123456 md5加密
        String password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(password);
        employee.setStatus(StatusConstant.ENABLE);
       // employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //Long empId = BaseContext.getCurrentId();
        //employee.setCreateUser(empId);
       // employee.setUpdateUser(empId);
        employeeMapper.insert(employee);
    }

    /**
     * 分页查询员工
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult<Employee> page(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        List<Employee> employeeList = employeeMapper.page(employeePageQueryDTO);
        Page<Employee> p=(Page<Employee>) employeeList;
        PageResult<Employee> pageResult=new PageResult(p.getTotal(),p.getResult());
        return pageResult;
    }

    /**
     * 状态查看
     * @param id
     * @param status
     */
    @Override
    public void modifyStatus(Long id, Integer status) {
        employeeMapper.modifyStatus(id,status);
    }

    @Override
    public void updateById(Long id,  Integer status) {
        Employee employee=new Employee();
        employee.setStatus(status);
        employee.setId(id);
       // employee.setUpdateUser(BaseContext.getCurrentId());
        //employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.updateById(employee);
    }

    /**
     * 根据员工id进行回显
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        return employeeMapper.getById(id);
    }

    @Override
    public void modifyById(EmployeeDTO employeeDTO) {
        checkParams(employeeDTO);
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        //employee.setUpdateTime(LocalDateTime.now());
        //Long empId = BaseContext.getCurrentId();
        //employee.setUpdateUser(empId);
        employeeMapper.updateById(employee);
    }

    private void checkParams(EmployeeDTO employeeDTO) {
        //“账号输入不符，请输入3-20个字符
        if (Objects.isNull(employeeDTO.getUsername()) ||
                employeeDTO.getUsername().length() < 3 ||
                employeeDTO.getUsername().length() > 20) {
            throw new AccountFormatException("账号输入不符，请重新输入");
        }
        //账号重复提示“账号重复，请调整”
        Integer countByusername =0;
        if (Objects.isNull(employeeDTO.getId())) {
             countByusername = employeeMapper.selectCountByusername(employeeDTO);
        } else {
            countByusername=employeeMapper.selectCountByusernameAndNotId(employeeDTO.getUsername(),employeeDTO.getId());
        }
        if (countByusername > 0) {
            throw new AccountDuplicateException("账号重复，请调整");
        }
        //不符合限制提示，“请输入正确的手机号“
        if (Objects.isNull(employeeDTO.getPhone()) ||
                employeeDTO.getPhone().length() != 11) {
            throw new PhoneFormatException("请输入正确的手机号");
        }
        //不符合限制提示，“ 身份证号码不正确”
        if (Objects.isNull(employeeDTO.getIdNumber()) ||
                employeeDTO.getIdNumber().length() != 18) {
            throw new IDCardFormatException("请输入正确的身份证号");
        }
    }


}
